package cn.jianml.log.aspect;

import cn.jianml.log.annotation.Log;
import cn.jianml.log.entity.SysLog;
import cn.jianml.log.utils.HttpContextUtil;
import cn.jianml.log.utils.IPUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * AOP 记录用户操作日志
 * @author wujian
 * @time 2020/1/8
 */
@Slf4j
@Aspect
@Component
public class LogAspect {

    @Pointcut("@annotation(cn.jianml.log.annotation.Log)")
    public void pointcut() {
        // do nothing
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) {
        Object result = null;
        long beginTime = System.currentTimeMillis();
        try{
            // 执行方法
            result = point.proceed();
        }catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        long time = System.currentTimeMillis() - beginTime;

        // 打印日志
        printLog(point, time);
        return result;
    }

    private void printLog(ProceedingJoinPoint joinPoint, long time){
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        SysLog sysLog = new SysLog();
        Log logAnnotation = method.getAnnotation(Log.class);
        if(logAnnotation != null) {
            // 注解上的描述
            sysLog.setOperation(logAnnotation.value());
        }

        // 请求方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        sysLog.setMethod(className + "." + methodName + "()");

        // 请求的方法参数值
        Object[] args = joinPoint.getArgs();
        // 请求的方法参数名称
        LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
        String[] paramNames = u.getParameterNames(method);
        if (args != null && paramNames != null) {
            String params = "";
            for (int i = 0; i < args.length; i++) {
                params += "  " + paramNames[i] + ": " + args[i];
            }
            sysLog.setParams(params);
        }
        // 获取request
        HttpServletRequest request = HttpContextUtil.getHttpServletRequest();
        // 设置IP地址
        sysLog.setIp(IPUtil.getIpAddr(request));
        // 模拟一个用户名
        sysLog.setUsername("admin");
        sysLog.setTime((int) time);
        sysLog.setCreateTime(new Date());
        // 打印系统日志(我们也可以在这里把系统日志存入数据库)
        log.info(sysLog.toString());

    }
}
